import { createVNode as _createVNode } from "vue";
import { ref, watch, computed, nextTick, Teleport, onMounted, defineComponent } from "vue";
import { isDef, isHidden, truthProp, numericProp, getScrollTop, preventDefault, makeNumberProp, 
  createNamespace, getRootScrollTop, setRootScrollTop } from "../utils/index.mjs";
import { useRect, useChildren, useScrollParent, useEventListener } from "@vant/use";
import { useTouch } from "../composables/use-touch.mjs";
import { useExpose } from "../composables/use-expose.mjs";
// 为配置props.indexList时,默认使用A-Z作为数据
// 将A转为对应码数, 26位字符递推, 转为对应字符串
function genAlphabet() {
  const charCodeOfA = "A".charCodeAt(0);
  const indexList = Array(26).fill("").map((_, i) => String.fromCharCode(charCodeOfA + i));
  return indexList;
}
const [name, bem] = createNamespace("index-bar");
const indexBarProps = {
  sticky: truthProp, // 是否开启锚点自动吸顶
  zIndex: numericProp, // z-index 层级
  teleport: [String, Object],
  highlightColor: String,
  stickyOffsetTop: makeNumberProp(0),
  indexList: { // 索引字符列表  
    type: Array,
    default: genAlphabet
  }
};
const INDEX_BAR_KEY = Symbol(name);
var stdin_default = defineComponent({
  name,
  props: indexBarProps,
  emits: ["select", "change"],
  setup(props, {
    emit,
    slots
  }) {
    const root = ref();
    const sidebar = ref();
    const activeAnchor = ref("");
    const touch = useTouch();
    const scrollParent = useScrollParent(root);
    // children为子组getCurrentInstance().proxy 
    // 通过useChildren的linkChildren 向子组件provide相应的props, 实现穿透传递
    const {
      children, // 为所有的anchor子组件 其它子组件未添加
      linkChildren
    } = useChildren(INDEX_BAR_KEY);
    // index为props.indexList的值
    let selectActiveIndex;
    linkChildren({
      props
    });

    // 电梯栏 的zindex计算属性
    const sidebarStyle = computed(() => {
      if (isDef(props.zIndex)) {
        return {
          zIndex: +props.zIndex + 1
        };
      }
    });
    // 获取高亮对应的展示颜色
    const highlightStyle = computed(() => {
      if (props.highlightColor) {
        return {
          color: props.highlightColor
        };
      }
    });
    // 获取active的anchor的arrIndex  scrollTop为上一级滚动节点的scrollTop  rects为所有anchor的rect集合
    const getActiveAnchor = (scrollTop, rects) => {
      // 反向遍历找到第一个符合 范围值的anchor
      for (let i = children.length - 1; i >= 0; i--) {
        const prevHeight = i > 0 ? rects[i - 1].height : 0;
        // 衔接时 当前和前一个anchor都是sticky
        // 只是active的是当前的
        const reachTop = props.sticky ? prevHeight + props.stickyOffsetTop : 0;
        if (scrollTop + reachTop >= rects[i].top) {
          return i;
        }
      }
      return -1;
    };

    // 获取 children中indexAnchor对应的实例, index为props.indexList中各项
    // 故props.indexList要和indexAnchor的 props.index 向对应
    const getMatchAnchor = (index) => children.find((item) => String(item.index) === index);

    // 滚动时, 切换电梯指示
    const onScroll = () => {
      if (isHidden(root)) {
        return;
      }
      const {
        sticky,
        indexList
      } = props;
      const scrollTop = getScrollTop(scrollParent.value);
      const scrollParentRect = useRect(scrollParent);
      // 获取各个Anchor的rect数据
      const rects = children.map((item) => item.getRect(scrollParent.value, scrollParentRect));
      let active = -1; // 当前active的ancor的arrIndex
      if (selectActiveIndex) {
        const match = getMatchAnchor(selectActiveIndex);
        // 点击右侧电梯栏后滚动  根据当前的anchor的rect信息计算
        if (match) {
          const rect = match.getRect(scrollParent.value, scrollParentRect);
          if (props.sticky && props.stickyOffsetTop) {
            active = getActiveAnchor(rect.top - props.stickyOffsetTop, rects);
          } else {
            active = getActiveAnchor(rect.top, rects);
          }
        }
      } else {
        active = getActiveAnchor(scrollTop, rects);
      }
      // 设定选中anchor的index
      activeAnchor.value = indexList[active];
      if (sticky) {
        children.forEach((item, index) => {
          const {
            state,
            $el
          } = item;
          // 存在两个sticky共存的情况, 分别设定sticky需要的样式
          // 前后两个分别设定 width和left, 其它位置的width和left分别置为null
          if (index === active || index === active - 1) {
            const rect = $el.getBoundingClientRect();
            state.left = rect.left;
            state.width = rect.width;
          } else {
            state.left = null;
            state.width = null;
          }
          // 设定衔接处 的 translate3d Y轴方向设定为top
          if (index === active) {
            state.active = true;
            state.top = Math.max(props.stickyOffsetTop, rects[index].top - scrollTop) + scrollParentRect.top;
          } else if (index === active - 1 && selectActiveIndex === "") {
            const activeItemTop = rects[active].top - scrollTop;
            state.active = activeItemTop > 0;
            state.top = activeItemTop + scrollParentRect.top - rects[index].height;
          } else {
            state.active = false;
          }
        });
      }
      selectActiveIndex = "";
    };

    // 初始化 计算位置 设定电梯栏的状态
    const init = () => {
      nextTick(onScroll);
    };

    useEventListener("scroll", onScroll, {
      target: scrollParent,
      passive: true
    });

    // 初次和props.indexList改变时 初始化
    onMounted(init);
    watch(() => props.indexList, init);
    // activeAnchor改变通知外部 emit
    watch(activeAnchor, (value) => {
      if (value) {
        emit("change", value);
      }
    });

    // 右侧电梯栏各项  渲染函数
    const renderIndexes = () => props.indexList.map((index) => {
      // index为电梯栏各项  展示文本
      // 是否为当前选中值
      const active = index === activeAnchor.value;
      return _createVNode("span", {
        "class": bem("index", {
          active
        }),
        "style": active ? highlightStyle.value : void 0,
        // dataset设定为idnex, 点击时获取
        "data-index": index
      }, [index]);
    });

    // indexBar滚动到相应位置, index为props.indexList的值
    const scrollTo = (index) => {
      selectActiveIndex = String(index);
      const match = getMatchAnchor(selectActiveIndex);
      // match为indexAnchor的实例
      if (match) {
        const scrollTop = getScrollTop(scrollParent.value);
        const scrollParentRect = useRect(scrollParent);
        const {
          offsetHeight
        } = document.documentElement;
        // 将match滚动到可见位置
        match.$el.scrollIntoView();
        if (scrollTop === offsetHeight - scrollParentRect.height) {
          onScroll();
          return;
        }
        // 根据stickyOffsetTop修正 fixed的位置
        if (props.sticky && props.stickyOffsetTop) {
          if (getRootScrollTop() === offsetHeight - scrollParentRect.height) {
            setRootScrollTop(getRootScrollTop());
          } else {
            setRootScrollTop(getRootScrollTop() - props.stickyOffsetTop);
          }
        }
        emit("select", match.index);
      }
    };
    // 获取电梯栏的index, 触发滚动
    const scrollToElement = (element) => {
      const {
        index
      } = element.dataset;
      if (index) {
        // 滚动到那个indexAnchor
        scrollTo(index);
      }
    };
    // 点击电梯栏项时
    const onClickSidebar = (event) => {
      scrollToElement(event.target);
    };

    let touchActiveIndex;
    const onTouchMove = (event) => {
      touch.move(event);
      if (touch.isVertical()) {
        preventDefault(event);
        const {
          clientX,
          clientY
        } = event.touches[0];
        const target = document.elementFromPoint(clientX, clientY);
        if (target) {
          const {
            index
          } = target.dataset;
          if (index && touchActiveIndex !== index) {
            touchActiveIndex = index;
            scrollToElement(target);
          }
        }
      }
    };
    // 右侧电梯栏 渲染函数
    const renderSidebar = () => _createVNode("div", {
      "ref": sidebar,
      "class": bem("sidebar"),
      "style": sidebarStyle.value,
      "onClick": onClickSidebar,
      "onTouchstartPassive": touch.start
    }, [renderIndexes()]);

    // 暴露外部使用
    useExpose({
      scrollTo
    });

    useEventListener("touchmove", onTouchMove, {
      target: sidebar
    });
    // 组件布局 van-index-bar[van-index-bar__sidebar div[van-index-anchor van-cell]]
    return () => {
      var _a;
      return _createVNode("div", {
        "ref": root,
        "class": bem()
      }, [props.teleport ? _createVNode(Teleport, {
        "to": props.teleport
      }, {
        default: () => [renderSidebar()]
      }) : renderSidebar(), (_a = slots.default) == null ? void 0 : _a.call(slots)]);
    };
  }
});
export {
  INDEX_BAR_KEY,
  stdin_default as default,
  indexBarProps
};
